import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, ActivityIndicator, RefreshControl, Alert } from 'react-native';
import { Stack, Link, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { Container } from '../../components/Container';
import apiService from '../../services/api';

// 主题数据类型
interface Theme {
  serialNo: string;
  title: string;
  description: string;
  amount: number;
  totalAmount: number;
  status: string;
  createTime: string;
  userId: string;
  userName?: string;
}

export default function ThemesScreen() {
  const router = useRouter();
  const [themes, setThemes] = useState<Theme[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 加载主题数据
  const loadThemes = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiService.themes.list();
      if (response.message === 'success' && response.data.themes) {
        setThemes(response.data.themes);
      } else {
        throw new Error(response.message || '获取数据失败');
      }
    } catch (err: any) {
      console.error('加载主题失败:', err);
      setError(err.message || '加载主题时发生错误');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 初始加载
  useEffect(() => {
    loadThemes();
  }, []);

  // 下拉刷新处理
  const handleRefresh = () => {
    setRefreshing(true);
    loadThemes();
  };

  // 格式化金额显示
  const formatAmount = (amount: number) => {
    return typeof amount === 'number' && !isNaN(amount) ? `¥${amount.toFixed(2)}` :  (amount == 0 || amount == null ? `¥0.00` : `¥${amount}`);
  };

  // 获取状态对应的颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return '#3B82F6'; // blue
      case 'closed':
        return '#6366F1'; // indigo
      default:
        return '#9CA3AF'; // gray
    }
  };

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  // 渲染单个主题项
  const renderItem = ({ item }: { item: Theme }) => {
    // 使用类型断言解决TypeScript类型问题
    return (
      <TouchableOpacity 
        className="bg-white rounded-lg shadow-sm p-4 mb-3"
        onPress={() => {
          router.push({
            pathname: '/themes/[id]',
            params: { id: item.serialNo }
          });
        }}
      >
        <View className="flex-row justify-between items-center mb-2">
          <Text className="font-bold text-gray-800 text-lg">{item.title}</Text>
          <View 
            className="px-2 py-1 rounded-full"
            style={{ backgroundColor: `${getStatusColor(item.status)}20` }}
          >
            <Text style={{ color: getStatusColor(item.status) }} className="text-xs font-medium">
              {item.status == 'active'?'进行中':item.status == 'closed'?'已关闭':'草稿'}
            </Text>
          </View>
        </View>
        
        <Text className="text-gray-500 mb-3" numberOfLines={2}>
          {item.description}
        </Text>
        
        <View className="flex-row justify-between items-center">
          <Text className="text-gray-500">{formatDate(item.createTime)}</Text>
          <Text className="font-bold text-blue-600">{formatAmount(item.totalAmount)}</Text>
        </View>
      </TouchableOpacity>
    );
  };

  // 渲染加载状态或错误信息
  const renderContent = () => {
    if (loading && !refreshing) {
      return (
        <View className="flex-1 justify-center items-center">
          <ActivityIndicator size="large" color="#3B82F6" />
          <Text className="mt-2 text-gray-500">加载中...</Text>
        </View>
      );
    }

    if (error) {
      return (
        <View className="flex-1 justify-center items-center p-4">
          <Ionicons name="alert-circle-outline" size={48} color="#EF4444" />
          <Text className="mt-2 text-gray-700 text-center">{error}</Text>
          <TouchableOpacity 
            className="mt-4 bg-blue-500 px-4 py-2 rounded-lg"
            onPress={loadThemes}
          >
            <Text className="text-white font-medium">重试</Text>
          </TouchableOpacity>
        </View>
      );
    }

    if (themes.length === 0) {
      return (
        <View className="flex-1 justify-center items-center p-4">
          <Ionicons name="folder-outline" size={48} color="#9CA3AF" />
          <Text className="mt-2 text-gray-700 text-center">暂无报销主题</Text>
          <TouchableOpacity 
            className="mt-4 bg-blue-500 px-4 py-2 rounded-lg"
            onPress={() => {
              // @ts-ignore - 忽略路由类型检查
              router.push('/themes/new');
            }}
          >
            <Text className="text-white font-medium">创建主题</Text>
          </TouchableOpacity>
        </View>
      );
    }

    return (
      <FlatList
        data={themes}
        renderItem={renderItem}
        keyExtractor={(item) => item.serialNo}
        contentContainerStyle={{ padding: 16 }}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
        }
      />
    );
  };

  return (
    <>
      <Stack.Screen
        options={{
          title: '报销主题',
          headerRight: () => (
            <TouchableOpacity 
              className="pr-4"
              onPress={() => {
                // @ts-ignore - 忽略路由类型检查
                router.push('/themes/new');
              }}
            >
              <Ionicons name="add-outline" size={24} color="#3B82F6" />
            </TouchableOpacity>
          )
        }}
      />
      <Container>
        {renderContent()}
      </Container>
    </>
  );
}